package com.tcheung.service.impl;

import com.pandawork.core.log.LogClerk;
import com.tcheung.common.entity.QueryResult;
import com.tcheung.service.QueryService;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * QueryServiceImpl
 *
 * @author: zhangteng
 * @time: 2014/12/14 14:21
 */
@Service("queryService")
public class QueryServiceImpl implements QueryService {

    public static final String FIELD_NAME = "content";

    public static final int MAX_NUM_FRAGMENTS_REQUIRED = 5;

    public static final String FRAGMENT_SEPARATOR = "...";
    @Autowired
    @Qualifier("luceneAnalyzer")
    private Analyzer luceneAnalyzer;

    @Autowired
    @Qualifier("luceneDirectory")
    private SimpleFSDirectory luceneDirectory;

    @Override
    public List<QueryResult> query(String queryContent) {
        List<QueryResult> queryResultList = new ArrayList<QueryResult>();
        try {
            IndexReader indexReader = IndexReader.open(luceneDirectory);
            IndexSearcher indexSearcher = new IndexSearcher(indexReader);

            QueryParser queryParser = new QueryParser(Version.LUCENE_45, FIELD_NAME, luceneAnalyzer);
            Query query = queryParser.parse(queryContent);

            TopDocs hits = indexSearcher.search(query, 30);
            int hitsLen = hits.scoreDocs.length;

            // 构建Fragmenter对象,用于文档切片
            Fragmenter fragmenter = new SimpleFragmenter();
            // 构建Scorer,用于选取最佳切片
            Scorer scorer = new QueryScorer(query);
            // 构建Formatter格式化最终显示(将字体颜色设置为红色)
            Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
            // 实例化Highlighter组件
            Highlighter highlighter = new Highlighter(formatter, scorer);

            for (int i = 0;i < hitsLen; ++i) {
                int docId = hits.scoreDocs[i].doc;
                Document document = indexSearcher.doc(docId);
                String title = document.get("title");
                QueryResult queryResult = new QueryResult();
                queryResult.setTitle(document.get("title"));
                queryResult.setName(title.substring(0, title.indexOf(".doc")));

                // 获取高亮结果
                String text = document.get(FIELD_NAME);
                TokenStream tokenStream = luceneAnalyzer.tokenStream(FIELD_NAME, new StringReader(text));


                String content = highlighter.getBestFragments(tokenStream, text, MAX_NUM_FRAGMENTS_REQUIRED, FRAGMENT_SEPARATOR);
                queryResult.setContent(content);

                queryResultList.add(queryResult);
            }
        } catch (Exception e) {
            LogClerk.errLog.error(e);
        }
        return queryResultList;
    }
}
